#include<signal.h>
#include<iostream>
#include"../comm/httplib.h"
#include"oj_control.hpp"
#include"../comm/spdlog.hpp"

static y_control::Control* ctrl_ptr=nullptr;

void Recovery(int signo)
{
    ctrl_ptr->RecoveryMachine();
}

int main(int argc, char *argv[])
{
    //初始化日志
    google::ParseCommandLineFlags(&argc, &argv, true);
    init_logger(FLAGS_run_mode,FLAGS_log_file,FLAGS_log_level);

    signal(SIGQUIT,Recovery);

    //用户请求服务路由功能
    httplib::Server svr;

    y_control::Control ctrl;
    ctrl_ptr=&ctrl;
    
    svr.Get("/all_questions",[&ctrl](const httplib::Request& req, httplib::Response& resp)
    {
        std::string html;
        ctrl.AllQueations(&html);
        resp.set_content(html,"text/html; charset=utf-8");
    }); 
    svr.Get(R"(/question/(\d+))",[&ctrl](const httplib::Request& req,httplib::Response& resp)
    {
        std::string number=req.matches[1];
        std::string html;
        ctrl.Question(number,&html);
        resp.set_content(html,"text/html; charset=utf-8");
    });
    //用户提交代码，使用判题功能
    svr.Post(R"(/judge/(\d+))",[&ctrl](const httplib::Request& req,httplib::Response& resp)
    {
        std::string number=req.matches[1];
        std::string result_json;
        ctrl.Judge(number, req.body, &result_json);
        resp.set_content(result_json, "application/json;charset=utf-8");
    });
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0",8080);
    return 0;
}
